const { Service } = require('egg')
const { encodeInp } = require('../utils/encryption')

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookieVPN() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data

      /* * 0. 请求门户主页获取jsessionid */
      // eslint-disable-next-line max-len
      const indexUrl = 'https://vpn.hufe.edu.cn/http/77726476706e69737468656265737421e5f60f9432366d1e7b0c9ce29b5b/sso/login?service=http://i.hufe.edu.cn/user/simpleSSOLogin'
      const indexRes = await ctx.curl(indexUrl, {
        method: 'GET',
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
      })
      const setCookie = indexRes.headers['set-cookie'] ? indexRes.headers['set-cookie'].map((e) => e.split(';')[0])[0] : ''
      const jsessionid = (indexRes.data.toString().match(/jsessionid=(\w+)?/) || ['', ''])[1]

      if (indexRes.status === 502) return { setCookie: '', status: 502 }
      console.log('setCookie', setCookie)
      /* end */

      /* * 1. 登录信息门户 */
      // eslint-disable-next-line max-len
      const loginUrl = `https://vpn.hufe.edu.cn/http/77726476706e69737468656265737421e5f60f9432366d1e7b0c9ce29b5b/sso/login;jsessionid=${jsessionid}?service=http://i.hufe.edu.cn/user/simpleSSOLogin`
      const loginRes = await ctx.curl(loginUrl, {
        method: 'POST',
        headers: {
          Cookie: setCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        },
        data: {
          /**
           * ! 登入门户的学号
           */
          username: '',
          /**
           * ! 登入门户的密码
           */
          password: encodeInp(''),
          validateCode: '',
          lt: 'e1s1',
          _eventId: 'submit',
        },
      })
      console.log('2', loginRes.status, loginRes.headers.location)
      /* end */

      /* * 2. 重定向教务登录主页 */
      const RedirectRes1 = await ctx.curl(`${ctx.state.baseUrl}/jsxsd`, {
        method: 'GET',
        headers: {
          Cookie: setCookie,
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
        followRedirect: true, // 允许重定向，模拟登录成功的关键操作
      })
      console.log('3', RedirectRes1.status)

      /* * 3.教务登录 */
      const loginRes2 = await ctx.curl(`${ctx.state.baseUrl}/jsxsd/xk/LoginToXk`, {
        method: 'POST',
        headers: {
          Cookie: setCookie,
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36',
        },
        data: {
          encoded: `${encodeInp(sid)}%%%${encodeInp(pwd)}`,
        },
      })
      console.log('4', loginRes2.status, loginRes2.headers.location)
      /* end */
      if (loginRes2.status === 302 && loginRes2.headers.location.includes('xsMain.jsp')) return { setCookie, status: 302 }
      if (loginRes2.status === 302 && !loginRes2.headers.location.includes('xsMain.jsp')) return { setCookie, status: 500 }

      return { setCookie, status: 200 }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }

  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data
      const encoded = `${encodeInp(sid)}%%%${encodeInp(pwd)}`
      const apiUrl = `${ctx.state.baseUrl}/jsxsd/xk/LoginToXk`

      const res = await ctx.curl(apiUrl, {
        method: 'POST',
        data: {
          encoded,
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
        },
        timeout: 10000,
      })
      const setCookie = res.headers['set-cookie'] ? res.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
      return { setCookie, status: res.status }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
